$(function () {
    var y;
    localStorage.removeItem('districtmsg');
    getPostion();
    getTag();
    changeTabs();

    $(document).on('click', '.J-praise', function () {
        var type = $(this).hasClass('praised') ? 1 : 0;
        $(this).toggleClass('praised');
        var postId = $(this).data('postid');
        Detail.clickPraise(postId, type,this);
    })

    setTimeout(function () {
        window.scrollTo(0, 0)
        window.onscroll = onscrollFn
    }, 1000);
    isAdmin();
    $('body').on('click',function (e) {
        console.log(e.target);
        if($(e.target).is('.add-tie')){
          $('.fa-tie').toggle()  
        }
        else{
            $('.fa-tie').hide()
        }
        //$('.fa-tie').toggle()
    });
    
})
//下拉刷新
function downReload() {
    var reload = $('.reload');
    $(window).on('touchstart', function (e) {
        y = e.targetTouches[0].pageY
    })
    $(window).on('touchmove', function (e) {
        var newy = e.changedTouches[0].pageY
        if (newy - y > 100 && y && !window.scrollY) {
            y = undefined
            reload.show(500);

            var ul = $('.dm-tab').find('ul');
            var tagid = ul.find('.cur-tab').data('id');
            var curMenquanPage = 1;
            var curActPage = 1;
            if (localStorage.getItem('districtmsg') == 'true') {

                getAct(tagid);
            }
            else {
                getMenquan(tagid);
            }

            setTimeout(function () {
                reload.hide()
            }, 1000)
        }
    });
    $('body').on('click',function(e){
        if(!$(e.target).is('.add-tie')){
            $('.fa-tie').hide();
        }
    })
}
// 对门 门圈 发现好生活
var changeTabs = function () {
    $('.dm-tabs').find('a').click(function () {
        var $this = $(this);
        $this.addClass('cur').siblings('a').removeClass('cur');
        var ul = $('.dm-tab').find('ul');
        var tagid = ul.find('.cur-tab').data('id');
        //debugger
        if ($this.text() == "小区消息") {
            localStorage.setItem('districtmsg', true)
            getAct(tagid);
        }
        else {
            localStorage.setItem('districtmsg', false)
            getMenquan(tagid)
        }
    });
}
// 
var changeTab = function () {
    $('.dm-tab').find('li').click(function () {
        var tagid = $(this).data('id');
        $(this).addClass('cur-tab').siblings('li').removeClass('cur-tab');
        console.log(tagid);
        getMenquan(tagid);
    })
}

//获取标签
var getTag = function () {
    //checkLogin(function(){
    $.ajax({
        url: baseurl + '/tag/list.html',
        dataType: 'jsonp',
    }).then(function (data) {
        ensureCorrectRes(data, function () {
            data.result.unshift({ "tagId": 0, "tagName": "首页" })
            var html = template('tag_tpl', data)
            var ul = $('.dm-tab').find('ul');
            ul.html(html);
            var width = 0;
            ul.find('li').each(function (i, li) {
                width += $(li).width()
            })
            ul.width(width + 20);
            var tagid = ul.find('.cur-tab').data('id');
            getMenquan(tagid);
            changeTab();
            downReload();
            if(getUrlParam('start')=='xiaoqu'){
                $('.dm-tabs').find('a:eq(1)').click();  
            }
        })
    })
    //})

}
//获取帖子
var getMenquan = function (tagId, pageNum, isAppend) {
    var pageNum = pageNum || 1;
    $.ajax({
        url: baseurl + '/post/query/common.html',
        dataType: 'jsonp',
        data: {
            poiId: Util.getCookie('xd_poiId'),
            pageNum: pageNum,
            tagId: tagId
        }
    }).then(function (data) {
        ensureCorrectRes(data, function () {
            tplRender(data, isAppend);
            if (data.result.length && isAppend) {
                curMenquanPage++;
                console.log('curMenquanPage++');
            }
            bindComment();
        });
        lockon = true;
    })


}

var tplRender = function (data, isAppend) {
    data.result.forEach(function (tie) {
        if (tie.postType) {
            switch (tie.postType) {
                case 1:
                    tie.postTypeChn = '公告';
                    break;
                case 2:
                    tie.postTypeChn = '投票';
                    break;
                case 3:
                    tie.postTypeChn = '活动';
                    break;
            }
        }
        else {
            tie.praiseListChn = tie.praiseList.map(function (praise) {
                return praise.custName
            }).join('、')
        }
        tie.postTime =  getDateDiff(tie.postTime);
    })
    var html = template('tie_tpl', data);
    if (isAppend) {
        $('.tiecontent').append(html);
    }
    else {
        $('.tiecontent').html(html);
    }
    bindLink()
    var mySwiper = new Swiper('.swiper-container', {
        speed: 1000,
        spaceBetween: 0,
        autoplay: 3000,
        onSlideChangeEnd: function (swiper) {
            var page = $(swiper.container[0].parentElement.nextElementSibling);
            var length = swiper.wrapper[0].childElementCount;
            page.html(swiper.activeIndex + 1 + '/' + length);
            if (!swiper.autoplaying) {
                swiper.startAutoplay();
            }
        }
    });
}

//
var getAct = function (tagId, pageNum, isAppend) {
    var pageNum = pageNum || 1;
    $.ajax({
        url: baseurl + '/post/query/act.html',
        dataType: 'jsonp',
        data: {
            poiId: Util.getCookie('xd_poiId'),
            pageNum: pageNum,
            tagId: tagId
        }
    }).then(function (data) {
        ensureCorrectRes(data, function () {
            if (data.result.length && isAppend) {
                curActPage++;
                console.log('curActPage++');
            }
            tplRender(data, isAppend);
        });
        lockon = true;
    })


}

var Detail = {
    clickPraise: function (postId, type,target) {
        checkLogin();
        $.ajax({
            url: baseurl + '/post/save/praise.do',
            type: 'GET',
            dataType: 'jsonp',
            data: {
                postId: postId,
                type: type
               }
        }).then(function (data) {
            if (data.resultCode == 0) {
                var userName =  getCookie2('nick') || getCookie2('nick2');
                var likeEle = $(target).parents('.tie-op').siblings('.tie-like');
                //type 0 为点赞 此时已经点赞成功
                var commentsEle = likeEle.find('ul');
                if(!type){
                    //之前没有赞
                    if(likeEle.find('br').length){
                        likeEle.empty();    
                        likeEle.append('<i class="up"></i>').append('<p>'+userName+'觉得很赞</p>').append(commentsEle);
                    }
                    else{
                        var p = likeEle.find('p');
                        p.text(userName+'、'+p.text())
                    }
                }
                else{
                    //取消赞成功
                    var p = likeEle.find('p'),ptext = p.text();
                    ptext = ptext.replace(userName+'、','').replace('、'+userName,'').replace(userName,'');
                    if(ptext=='觉得很赞'){
                        ptext=''
                        p.siblings('.up').remove()
                        $('<br>').insertBefore(p);
                    }
                    p.text(ptext)

                }
                
                console.log(userName,target,type);
                //Detail.getCommPraise(postId);//获取评论点赞
            } else {
                console.log(data.resultMsg);
            }
        })
    },
    getCommPraise: function (postId) {
        $.ajax({
            type: 'GET',
            url: baseurl + '/post/query/commPraise',
            dataType: 'jsonp',
            data: {
                postId: postId
            }
        }).then(function (data) {
            if (data.resultCode == 0) {
                console.log('fuck', data);
                // var html = template('tpl_commentsList', data.result[0].commentVo);
                // var praiseHtml = template('tpl_praiseList',data.result[0].praiseVo)
                // $('.tie-comments>ul').html(html);
                // $('.tie-like').html(praiseHtml);
                // Detail.getCommentSum(postId,data.result[0].commentVo.totalPageCount);
            } else {
                console.log(data.resultMsg)
            }
        })
    },
    getCommentSum: function (postId, totalPageCount) {
        var commentSum = 0;
        var index = 0;
        for (var i = 1; i <= totalPageCount; i++) {
            $.ajax({
                type: 'GET',
                url: baseurl + '/post/query/commentsMore.json',
                dataType: 'jsonp',
                data: {
                    postId: postId,
                    pageNum: i
                }
            }).then(function (data) {
                if (!data.resultCode) {
                    commentSum = commentSum + data.result.cuList.length;
                    index++;
                    if (index == totalPageCount) {
                        $('#commentsSum').html('所有评论(' + commentSum + ')');
                    }
                } else {
                    console.log(data.resultMsg)
                }
            })
        }
    },
}

// 小区活动链接
var bindLink = function () {
    $('.tie-act,.tie-mod').off('click').click(function (e) {
        var postid = $(this).data('id');
        if ($(this).is('.tie-act')) {
            var type = $(this).find('span').text();
            if (type == "活动") {
                location.href = "detail/detail-sign.html?postType=3&postId=" + postid;
            }
            if (type == '公告') {
                location.href = "detail/detail-sign.html?postType=1&postId=" + postid;
            }
            if (type == "投票") {
                location.href = "vote/vote.html?postType=2&postid=" + postid;
            }
        }
        else {
            location.href = "detail/detail.html?postType=0&postId=" + postid;
        }
    })
}

var bindComment = function () {
    $('.J-comm').off('click').click(function (e) {
        var postid = $(this).parents('.tie-op').siblings('.tie-mod').data('id');
        location.href = "/duimen/detail/comment.html?postId=" + postid;
    });
    $('.com-cnt').off('click').find('li').click(function (e) {
        var postid = $(this).parents('.tie-like').siblings('.tie-mod').data('id');
        var repliedCustNo = $(this).data('custno');

        var custName = $(this).find('em').text();
        location.href = "/duimen/detail/comment.html?postId=" + postid + "&repliedCustNo=" + repliedCustNo +
            "&custName=" + custName;
    })
}

var curMenquanPage = 1;
var curActPage = 1;
var lockon = true;
//滚动到底部 加载下一页
var onscrollFn = function (e) {
    if (document.body.clientHeight - window.screen.height - window.scrollY < 10 && lockon) {
        lockon = false;
        var ul = $('.dm-tab').find('ul');
        var tagid = ul.find('.cur-tab').data('id');
        console.log(curMenquanPage, curActPage);
        if (localStorage.getItem('districtmsg') == 'true') {
            //小区消息
            getAct(tagid, curActPage + 1, true);
        }
        else {
            //门圈
            getMenquan(tagid, 1 + curMenquanPage, true);
        }

    }
}

var getPostion = function () {
    Prepare({
        complete: function (location) {
            if (Util.getCookie('xd_poiName')) {
                var name = Util.getCookie('xd_poiName');
                $('.makePosition').text(name);
            }
            else if (location && location.poiName) {
                Util.setCookie('xd_poiName', location.poiName)
                Util.setCookie('xd_poiId', location.poiId)
                $('.makePosition').text(location.poiName)
            }
            else {
                window.location.href = "/duimen/position.html"
            }
            $('.makePosition').click(function () {
                window.location.href = "/duimen/position.html"
            })
        }
    });
}
var isAdmin = function () {
    $.ajax({
        url: baseurl + '/user/adminInfo.do',
        dataType: 'jsonp',
        success: function (data) {
            if (data.resultCode == 0) {
                if (data.result.admin == 'False' || data.result.admin == 'false' || data.result.admin == false) {
                    
                }
                else{
                    $('.fa-tie').find('.admin').show();
                }
            }
        }
    })
}